//
//  CMCatchDollViewController.m
//  CraneMachine
//
//  Created by ice on 2017/10/31.
//  Copyright © 2017年 ICE. All rights reserved.
//

#import "CMCatchDollViewController.h"
#import "UIColor+Utility.h"
#import "CMDollListModel.h"
#import "NSTimer+Utility.h"
#import "QYGRechargeView.h"
#import "DDCoverView.h"
#import "QYGDrollTipView.h"
#import "QYGUserView.h"
#import "QYGCurrentRoomView.h"
#import "QYGCurrentRoomFrameEntity.h"
#import "DDSendView.h"
#import "QYGGameModel.h"
#import "QYGGameCompleteTipView.h"
#import "QYGNetRequestModel.h"
#import "QYGDrollRecordViewController.h"
#import "SocketIOTool.h"
#import "CMDollListModel.h"
#import "QYGRoomChangedModel.h"
#import "DetailMainView.h"
#import "QYGCoinRecordModel.h"
#import "LCCountdownView.h"
#import "QYGWebViewController.h"
#import "MyAVAudioPlayer.h"
#import "QYGDollBottomView.h"
#import "QYGDollLoadingView.h"
#import <QYGLivePlaySDK/QYGLivePlaySDK.h>

@interface CMCatchDollViewController ()<QYGLivePlayManagerDelegate,LCCountdownViewDelegate,QYGCommandManagerDelegate>
/**围观者前播放器*/
@property (nonatomic, strong) QYGLivePlayManager * playManager;
/**围观前置摄像头播放view*/
@property (nonatomic, strong) UIView * f_livePlayerView;
/**围观侧置摄像头播放view*/
@property (nonatomic, strong) UIView * s_livePlayerView;

@property (strong, nonatomic) UIView *containerView;
@property (nonatomic, strong) QYGDollBottomView *dollBottomView;
@property (strong, nonatomic) UILabel *timeLabel;
@property (strong, nonatomic) QYGDollLoadingView *loadingView;
/**游戏操作者*/
@property (nonatomic, strong) QYGUserView *userView;
/**顶部围观view*/
@property (nonatomic, strong) QYGCurrentRoomView *currentRoomView;
/**切换视频角度*/
@property (strong, nonatomic) UIButton *changeBtn;
/**剩余时间*/
@property (strong, nonatomic) NSTimer *timer;
@property (nonatomic, assign) NSInteger leftTime;
@property (nonatomic, strong) QYGGameMessageModel *gameMessageModel;
@property (nonatomic, strong) CMDollListModel *model;

@property (nonatomic, assign) BOOL isInGame;
@property (nonatomic, assign) BOOL isNoCanBack;
/**是否监听游戏进入下一局*/
@property (nonatomic, assign) BOOL isSubscribeNextGame;
/**是否是侧面*/
@property (nonatomic, assign) BOOL isSide;

@property (nonatomic, strong) SocketIOTool* socketTool;
@property (nonatomic, strong) QYGCommandManager* commandM;
// 播放音乐按钮
@property (nonatomic, strong) UIButton* songBtn;
/**当前游戏可操作状态*/
@property (nonatomic ,assign) CatchStartBtnMode starBtnMode;
///倒数view
@property (strong, nonatomic) LCCountdownView *countdownView;

/// 进入后台的时间
@property (nonatomic, strong) NSDate * goBackgroundDate;


@end

@implementation CMCatchDollViewController


- (instancetype)initWithModel:(CMDollListModel *)model {
    if (self = [super init]) {
        self.model = model;
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];
    [self loginRoom];
    [self setSocketData];
    
    [self getDetailData];
    
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    
    // 播放音乐
    [[MyAVAudioPlayer sharedAVAudioPlayer] playMusicWithMusicName:@"music"];
    WS(weakSelf);
    [[SGUtil shareUtil] setRechargeBlock:^(BOOL isSuccess, QYGCoinListModel *coinListModel) {
        [weakSelf.view makeToast:isSuccess ? @"支付成功！" :@"支付失败！"];
        if(isSuccess){
            weakSelf.userInfo.coin =  weakSelf.userInfo.coin + coinListModel.coin + coinListModel.coin_award;
            weakSelf.userInfo.coin_buy = weakSelf.userInfo.coin_buy + coinListModel.coin + coinListModel.coin_award;
            [weakSelf.dollBottomView updateTotalCoin:[NSString stringWithFormat:@"%ld", weakSelf.userInfo.coin]];
        }
    }];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    [self addNoti];
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [[MyAVAudioPlayer sharedAVAudioPlayer] stopMusic];
    if(self.countdownView){
        [self.countdownView removeFromSuperview];
    }
    
}

- (void)dealloc {
    
    if(self.timer){
        
        [self.timer invalidate];
        self.timer = nil;
    }
    
    [self stopRtmp];
    [self.commandM disConnect];
    self.commandM = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self subscribeNextGame:NO];
    [self.socketTool socketDisConnect];
    [QYGNetRequestModel postEnterOrExitRoomWithDeviceId:self.model.device_id Action:RoomActionTypeExit completed:^(BOOL isSuccess) {
    } WithErrorCodeBlock:^(NSError *error) {
    }];
    
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
}
#pragma  mark - QYGCommandManagerDelegate
-(void)webSocketDidOpend{
    QYLog(@"-------连接成功");
}

- (void)webSocketDidReceiveMsg:(id)message{
    QYLog(@"-----获取数据");
}
- (void)webSocketLinkIsNotNormalWithMessage:(NSError *)error{
    QYLog(@"--链接不正常，会尝试再次链接");
}
- (void)webSocketDidClosedWithCode:(NSInteger)code reason:(NSString *)reason{
    
    QYLog(@"--链接被关闭");
}
- (void)webSocketDidFailed{
    
    QYLog(@"--链接失败");
}

#pragma  mark -加入房间
- (void)loginRoom{
    WS(weakSelf);
    [self.playManager loginWithRoomID:self.model.room_id userID:[NSString stringWithFormat:@"%ld",(long)self.userInfo.userId] token:self.userInfo.video_token completeBlock:^(NSError *error) {
        if(!error){
            [weakSelf startRtmp];
        }
    }];
}
#pragma  mark 开始播放围观流
-(BOOL)startRtmp{
    //设置当前视频展示方向
    [self.playManager setFrontRotation:HOME_ORIENTATION_RIGHT];
    [self.playManager setSideRotation:HOME_ORIENTATION_RIGHT];
    
    [self.playManager startPlayFrontWithContainView:self.f_livePlayerView isLive:NO errorBlock:nil];
    [self.playManager startPlaySideWithContainView:self.s_livePlayerView isLive:NO errorBlock:nil];
    return YES;
}


- (void)stopRtmp{
    [self.playManager stopPlaySide];
    [self.playManager stopPlayFront];
}

#pragma  mark 流播放回调
-(void) onPlayEvent:(int)EvtID withParam:(NSDictionary*)param {
    NSLog(@"onPlayEvent EvtID = %d", EvtID);
    dispatch_async(dispatch_get_main_queue(), ^{
        if (EvtID == PLAY_EVT_PLAY_BEGIN) {
            self.loadingView.hidden = YES;
        } else{ //if (EvtID == PLAY_EVT_PLAY_LOADING) {
            self.loadingView.hidden = NO;
        }
    });
    
}

#pragma mark - setUI
- (void)initUI {
    self.view.backgroundColor = [UIColor qyg_mainColor];
    
    [self.dollBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view);
        make.right.mas_equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom).offset(-SafeBottom);
        make.height.equalTo(@(ScaleW(149)));
    }];
    
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(ScaleW(0));
        make.left.equalTo(self.view.mas_left).offset(ScaleW(15));
        make.right.equalTo(self.view.mas_right).offset(ScaleW(-15));
        make.bottom.equalTo(self.dollBottomView.mas_top);
    }];
    
    
    [self.containerView addSubview:self.loadingView];
    [self.loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.containerView);
    }];
    [self.containerView addSubview:self.f_livePlayerView];
    [self.containerView addSubview:self.s_livePlayerView];
    
//    [self.containerView addSubview:self.m_txlivePlayerContentView];
//    [self.m_txlivePlayerContentView addSubview:self.fm_txlivePlayerView];
//    [self.m_txlivePlayerContentView addSubview:self.sm_txlivePlayerView];
    
    [self.f_livePlayerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.containerView.mas_left);
        make.right.equalTo(self.containerView.mas_right);
        make.top.equalTo(self.containerView.mas_top);
        make.bottom.equalTo(self.containerView.mas_bottom);
    }];
    
    [self.s_livePlayerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.containerView.mas_left);
        make.right.equalTo(self.containerView.mas_right);
        make.top.equalTo(self.containerView.mas_top);
        make.bottom.equalTo(self.containerView.mas_bottom);
    }];
    
    self.f_livePlayerView.hidden = NO;
    self.s_livePlayerView.hidden = YES;
    
    [self.containerView addSubview:self.changeBtn];
    [self.changeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.containerView.centerY);
        make.right.equalTo(self.containerView);
        make.size.mas_equalTo(CGSizeMake(ScaleW(35), ScaleW(38)));
    }];
    
    [self.containerView addSubview:self.songBtn];
    [self.songBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.bottom.mas_equalTo(-20);
        make.size.mas_equalTo(CGSizeMake(ScaleW(25), ScaleW(21)));
    }];
    
    [self.containerView addSubview:self.userView];
    self.userView.hidden = YES;
    [self.userView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.containerView.mas_top).offset(ScaleW(5));
        make.left.equalTo(self.containerView.mas_left).offset(ScaleW(5));
        make.size.mas_equalTo(CGSizeMake(ScaleW(105), ScaleW(34)));
    }];
    
    [self.containerView addSubview:self.currentRoomView];
    
    self.timeLabel.hidden = YES;
    [self.containerView addSubview:self.timeLabel];
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.containerView.mas_right).offset(-10);
        make.bottom.equalTo(self.containerView.mas_bottom).offset(-10);
        make.height.equalTo(@(ScaleW(32)));
        make.width.equalTo(@(ScaleW(120)));
    }];
    [self.dollBottomView updateOnceCoin:[NSString stringWithFormat:@"%ld金币/次",(long)self.model.coin]];
    // 设置总余额
    [self.dollBottomView updateTotalCoin:[NSString stringWithFormat:@"%ld",(long)self.userInfo.coin]];
    
    
}
#pragma mark - LCCountdownViewDelegate
- (void) countdownFinished:(LCCountdownView *)view
{
    [self.countdownView removeFromSuperview];
    
}
#pragma mark - Socket返回
- (void)startButtonClick:(CatchStartBtnMode) starBtnMode {
    if(self.userInfo.coin < self.model.coin){
        [self showTipViewWithState:DrollTipStateBalanceLack];
        return;
    }
    if(starBtnMode == CatchStartBtnModeCanStart){//开始游戏
        [self downloadData];
    }else if(starBtnMode == CatchStartBtnModeCanOrder){// 开始排队
        self.dollBottomView.starBtnMode = CatchStartBtnModeLineup;
        [self subscribeNextGame:YES];
        
    }else if(starBtnMode == CatchStartBtnModeLineup){//正在排队
        //取消排队
        self.dollBottomView.starBtnMode = CatchStartBtnModeCanOrder;
        // 取消监听游戏进入下一局
        [self subscribeNextGame:NO];
    }
}
- (void)showDetailView{
    
    DetailMainView *detailMianView = [[DetailMainView alloc] initWithFrame:CGRectMake(0, 0,ScaleW(315), SCREEN_WIDTH * 1.17)];
    detailMianView.deviceId = self.model.device_id;
    detailMianView.detail_img = self.model.detail_image;
    DDCoverView *coverView = [[DDCoverView alloc] initWithSize:detailMianView.size subView:detailMianView];
    coverView.isShowCancelImage = YES;
    [coverView showInView:KeyWindow];
}
- (void)setSocketData{
    
    WS(weakSelf);
    NSString *channal1 = [NSString stringWithFormat:@"machines.%ld",(long)self.model.device_id];
    NSString *channal2 = [NSString stringWithFormat:@"presence-machines.%ld.spectators",(long)self.model.device_id];
    
    [self.socketTool socketConnectWithChannel:@[channal1, channal2] completed:^(BOOL isSuccess) {
        [weakSelf performSelector:@selector(delayMethod) withObject:nil/*可传任意类型参数*/ afterDelay:0.5];
    }];
    
    // 围观者事件改变
    QYGCurrentRoomFrameEntity *currRoomFentity = [[QYGCurrentRoomFrameEntity alloc] init];
    [self.socketTool spectatorsChangedComplete:^(QYGRoomChangedModel *roomChangeModel) {
        currRoomFentity.roomChangeModel = roomChangeModel;
        
        weakSelf.currentRoomView.currRoomFEntity = currRoomFentity;
        weakSelf.currentRoomView.frame = CGRectMake(weakSelf.containerView.width - currRoomFentity.currRoomWith + ScaleW(20), ScaleW(5), currRoomFentity.currRoomWith, currRoomFentity.currRoomHeight);
    }];
    // 设备状态改变
    [self.socketTool setMachineStatusChangedBlock:^(QYGDeviceStateChangedModel *deviceStateModel) {
        if(deviceStateModel.device_status == 0){ //空闲状态
            weakSelf.userView.hidden = YES;
            weakSelf.dollBottomView.starBtnMode = CatchStartBtnModeCanStart;
            // 空闲状态
        }else if(deviceStateModel.device_status == 1){// 游戏中
            weakSelf.userView.hidden = NO;
            [weakSelf.userView userViewWithName:deviceStateModel.nickname headerStr:deviceStateModel.avatar];
            weakSelf.dollBottomView.starBtnMode = CatchStartBtnModeCanOrder;
        }
        // 判断当前抓取结果
        if(deviceStateModel.game_record_id && weakSelf.gameMessageModel.data.record_id == deviceStateModel.game_record_id){
            [weakSelf showGameResultWithGameResultModel:deviceStateModel.game_operate_result];
        }
    }];
    
}

#pragma mark - 内部方法

- (void)getDetailData{
    
    self.dollBottomView.userInteractionEnabled = NO;
    [QYGNetRequestModel getDrollMachineItemDataWithDevice_id:self.model.device_id completed:^(QYGMachineItemModel *machineItemModel) {
        // 获取当前设备状态 和排队人数
        self.dollBottomView.starBtnMode = !machineItemModel.device_status && !machineItemModel.queue_length ? CatchStartBtnModeCanStart : CatchStartBtnModeCanOrder;
        self.dollBottomView.userInteractionEnabled = YES;
        
        if(machineItemModel.player.avatar.length && machineItemModel.player.nickname.length){
            
            self.userView.hidden = NO;
            [self.userView userViewWithName:machineItemModel.player.nickname headerStr:machineItemModel.player.avatar];
        }
        
    } WithErrorCodeBlock:^(NSError *error) {
        self.dollBottomView.userInteractionEnabled = YES;
    }];
}

- (void)delayMethod{
    [QYGNetRequestModel postEnterOrExitRoomWithDeviceId:self.model.device_id Action:RoomActionTypeEnter completed:^(BOOL isSuccess) {
    } WithErrorCodeBlock:^(NSError *error) {
    }];
}
// 开始游戏
- (void)readyStartGame{
    
    // 开始播放直播流
    [self.playManager startPlayFrontWithContainView:self.f_livePlayerView isLive:YES errorBlock:nil];
    [self.playManager startPlaySideWithContainView:self.s_livePlayerView isLive:YES errorBlock:nil];
    
    [KeyWindow addSubview:self.countdownView];
    [self.countdownView updateAppearance];
    [self.countdownView start];
    
    self.commandM.delegate = self;
    [self.commandM connectWithUrlStr:self.gameMessageModel.data.ws_url];
    
    self.isInGame = YES;
    self.isNoCanBack = YES;
    [self startTime];
    // 订阅进入下一轮事件
    [self subscribeNextGame:YES];
}
- (void)downloadData {
    
    KeyWindow.userInteractionEnabled = NO;
    WS(weakSelf);
    [QYGNetRequestModel postGameWithDevice_id:self.model.device_id completed:^(QYGGameMessageModel *gameMessageModel) {
        
        if(gameMessageModel.code == 0){
            weakSelf.gameMessageModel = gameMessageModel;
            
            [weakSelf readyStartGame];
        }else if(gameMessageModel.code == 1001){
            KeyWindow.userInteractionEnabled = YES;
            [weakSelf showTipViewWithState:DrollTipStateBalanceLack];
        }else if (gameMessageModel.code == 1002){
            KeyWindow.userInteractionEnabled = YES;
            weakSelf.dollBottomView.starBtnMode = CatchStartBtnModeLineup;
            [weakSelf subscribeNextGame:YES];
        }
        
    } WithErrorCodeBlock:^(NSError *error) {
        KeyWindow.userInteractionEnabled = YES;
        [weakSelf showToast:@"请稍后再试!"];
    }];
}

- (void)startTime{
    
    KeyWindow.userInteractionEnabled = YES;
    self.dollBottomView.isHiddenStartView = YES;
    self.leftTime = self.gameMessageModel.data.time;
    self.timeLabel.hidden = NO;
    WS(weakSelf);
    self.timer = [NSTimer cm_scheduledTimerWithTimeInterVal:1 block:^{
        [weakSelf showCountTime];
    } repeats:YES];
    [self.timer fire];
}

- (void)catchDoll:(NSInteger)action {
    if(action == 5){
        self.isNoCanBack = NO;
        [self.timer invalidate];
        self.timer = nil;
         self.dollBottomView.userInteractionEnabled = NO;
    }
    [self.commandM sendCommand:action];
    
}
- (void)showGameResultWithGameResultModel:(NSInteger )result{
    [self.commandM disConnect];
    
    [self.playManager startPlayFrontWithContainView:self.f_livePlayerView isLive:NO errorBlock:nil];
    [self.playManager startPlaySideWithContainView:self.s_livePlayerView isLive:NO errorBlock:nil];
    self.isInGame = NO;
    
    // 显示返回成功
    self.dollBottomView.userInteractionEnabled = YES;
    self.dollBottomView.isHiddenStartView = NO;
    self.timeLabel.hidden = YES;
    self.dollBottomView.starBtnMode = CatchStartBtnModeCanStart;
    self.userInfo.coin -= self.model.coin;
    [self.dollBottomView updateTotalCoin:[NSString stringWithFormat:@"%ld",self.userInfo.coin]];
    [self showTipViewWithState:result == 1 ? DrollTipStateSucceed : DrollTipStateFail];
}

- (void)showTipViewWithState:(DrollTipState)drollState{
    
    if(drollState == DrollTipStateBalanceLack){
        [self subscribeNextGame:NO];
    }
    QYGDrollTipView *tipview = [[QYGDrollTipView alloc] initWithFrame:CGRectMake(0, 0, ScaleW(230), ScaleW(240))];
    tipview.drollState = drollState;
    DDCoverView *coverView = [[DDCoverView alloc] initWithSize:tipview.size subView:tipview];
    coverView.isShowCancelImage = NO;
    coverView.isNoClick = YES;
    [coverView showInView:KeyWindow];
    WS(weakSelf);
    __weak typeof(coverView) weakCoverView = coverView;
    [tipview setCancelBlock:^(DrollTipState drollState) {
        if(drollState == DrollTipStateSucceed){
            [self startGame];
        }else if (drollState == DrollTipStateFail){
            [weakSelf subscribeNextGame:NO];
        }else{
            [weakSelf subscribeNextGame:NO];
        }
        [weakCoverView hidden];
    }];
    
    [tipview setSuerBlock:^(DrollTipState drollState) {
        if(drollState == DrollTipStateSucceed){
            [weakSelf subscribeNextGame:NO];
            QYGWebViewController *webViewVC = [[QYGWebViewController alloc] init];
            webViewVC.urlStr = [NSString stringWithFormat:@"%@/?#/mywawa?api_token=%@",[QYGKeychain mall_url],[QYGKeychain token]];
            webViewVC.titleStr = @"我的娃娃";
            [weakSelf.navigationController pushViewController:webViewVC animated:YES];
        }else if (drollState == DrollTipStateFail){ //再抓一次
            [self startGame];
        }else{// 去充值
            [weakSelf getRechargeList];
        }
        [weakCoverView hidden];
    }];
    [tipview setStartBlock:^{
       //开始游戏
        [weakCoverView hidden];
        [weakSelf downloadData];
    }];
    [tipview setHiddenBlock:^{
        [weakCoverView hidden];
        [weakSelf subscribeNextGame:NO];
    }];
    return;
}
- (void)startGame{
    
    if(self.userInfo.coin < self.model.coin){
        [self showTipViewWithState:DrollTipStateBalanceLack];
        return;
    }
    [self downloadData];
}
- (void)subscribeNextGame:(BOOL)isSub{
    
    NSString *channal3 = [NSString stringWithFormat:@"presence-machines.%ld.player_queue",(long)self.model.device_id];
    // 开始监听游戏进入下一局
    if(!isSub){
        self.isSubscribeNextGame = NO;
        [self.socketTool gameNextOffWithChannel:channal3];
        return;
    }
    if(!self.isSubscribeNextGame){
        self.isSubscribeNextGame = YES;
        WS(weakSelf);
        [self.socketTool gameNextOnWithChannel:channal3 Complete:^(NSString *userid) {
            if(userid.integerValue == weakSelf.userInfo.userId){
                // 弹框可以开始游戏
                [weakSelf showTipViewWithState:DrollTipStateCanStart];
            }
        }];
    }
}

- (void)showCountTime {
    
    if (self.leftTime <= 0) {
        self.timeLabel.text = @"已结束";
        [self.timer invalidate];
        self.timer = nil;
        [self catchDoll:5];
    }
    
    NSString *time = [NSString stringWithFormat:@"%@s", @(self.leftTime)];
    self.timeLabel.text = time;
    
    self.leftTime--;
    
}

- (void)getRechargeList{
    WS(weakSelf);
    [SVProgressHUD show];
    [QYGNetRequestModel getCoinsListCompleted:^(NSArray *coinListArr) {
        [SVProgressHUD dismiss];
        [weakSelf rechargeWithCoinListArr:coinListArr];
    } WithErrorCodeBlock:^(NSError *error) {
    }];
    
}
- (void)actionButtonDownClick:(NSInteger)act {
    //手指按下, 移动
    NSInteger action = 0;
    if(!self.isSide){
        action = act;
    }else{
        if(act == 3)
        {
            action = ACTION_FORWARD;
        }else if(act == 4){
            action = ACTION_BACK;
        }else if(act == 1){
            action = ACTION_RIGHT;
        }else if(act == 2){
            action = ACTION_LEFT;
        }else{
            action = ACTION_DONE;
        }
    }
    [self catchDoll:action];
    
}
- (void)actionButtonOnClicked:(NSInteger)act{
    
    NSInteger action = 0;
    if(!self.isSide){
        action = act + 5;
    }else{
        if(act == 3){
            action = ACTION_FORWARD_STOP;
        }else if(act == 4){
            action = ACTION_BACK_STOP;
        }else if(act == 1){
            action = ACTION_RIGHT_STOP;
        }else if(act == 2){
            action = ACTION_LEFT_STOP;
        }
    }
    
    [self catchDoll:action];
}
/**
 充值
 */
- (void)rechargeWithCoinListArr:(NSArray *)coinListArr{
    
    if(!coinListArr.count){
        [self.view makeToast:@"没有数据"];
        return;
    }
    CGFloat h = ScaleW(70);
    if(coinListArr.count > 4){
        h = h + ScaleW(82.5) * 4.5;
    }else{
        h = h + ScaleW(82.5) * coinListArr.count;
    }
    QYGRechargeView *rechargeView = [[QYGRechargeView alloc] initWithFrame:CGRectMake(0, 0, ScaleW(315),h)];
    rechargeView.coinListArr = coinListArr;
    WS(weakSelf);
    DDCoverView *coverView = [[DDCoverView alloc] initWithSize:rechargeView.size subView:rechargeView];
    coverView.isShowCancelImage = YES;
    [coverView showInView:KeyWindow];
    
    __weak typeof(coverView) weakCoverView = coverView;
    [rechargeView setCloseBlock:^{
        [weakCoverView hidden];
    }];
    
    [rechargeView setRechargeBlock:^(BOOL isSuccess, QYGCoinListModel *coinListModel) {
        [weakSelf.view makeToast:isSuccess ? @"支付成功！" :@"支付失败！"];
        if(isSuccess){
            weakSelf.userInfo.coin =  weakSelf.userInfo.coin + coinListModel.coin + coinListModel.coin_award ;
            weakSelf.userInfo.coin_buy = weakSelf.userInfo.coin_buy + coinListModel.coin + coinListModel.coin_award;
            [weakSelf.dollBottomView updateTotalCoin:[NSString stringWithFormat:@"%ld", weakSelf.userInfo.coin]];
        }
        [weakCoverView hidden];
    }];
}

#pragma mark - 监听进入后台

- (void)appGoBackgroud
{
    if(!self.isInGame) return;
    self.goBackgroundDate = [NSDate date];
    self.timer.fireDate = [NSDate distantFuture];
    
}

- (void)appGoForegroud
{
    if(!self.isInGame) return;
    self.timer.fireDate = [NSDate distantFuture];
    int  timeGone = (int)[[NSDate date] timeIntervalSinceDate:self.goBackgroundDate];
    
    self.leftTime = self.leftTime - timeGone;
    if(self.leftTime <0){
        [self.timer invalidate];
        [self.commandM disConnect];
        self.userView.hidden = YES;
        self.isNoCanBack = NO;
        self.isInGame = NO;
        self.dollBottomView.userInteractionEnabled = YES;
        self.dollBottomView.isHiddenStartView = NO;
        self.timeLabel.hidden = YES;
        self.dollBottomView.starBtnMode = CatchStartBtnModeCanStart;
        self.userInfo.coin -= self.model.coin;
        [self.dollBottomView updateTotalCoin:[NSString stringWithFormat:@"%ld",self.userInfo.coin]];
        
        return;
    }
    
    self.timer.fireDate = [NSDate distantPast];
    
}

- (void)addNoti
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appGoBackgroud) name:AppGoBackgroud object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appGoForegroud) name:AppGoForegroud object:nil];
}
#pragma mark - target

/**
 音乐播放
 */
- (void)songBtnClicked:(UIButton *)songBtn{
    songBtn.selected = !songBtn.selected;
    [QYGKeychain setBgMusicIsClose:songBtn.selected];
    [[MyAVAudioPlayer sharedAVAudioPlayer] playOrStopMusic];
}

/**
 切换摄像头
 */
- (void)changeLiveUrl:(UIButton*)button {
    button.selected = !button.selected;
    
        if (button.selected) {
            self.isSide = YES;
            self.f_livePlayerView.hidden = YES;
            self.s_livePlayerView.hidden = NO;
            //    娃娃机01侧面
        } else {
            
            self.isSide = NO;
            //    娃娃机01正面
            self.f_livePlayerView.hidden = NO;
            self.s_livePlayerView.hidden = YES;
        }
}

- (void)back{
    
    if(self.isNoCanBack){
        [self.view makeToast:@"游戏中，请勿退出！"];
        return;
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - lazy

- (QYGCommandManager *)commandM{
    if(!_commandM){
        _commandM = [QYGCommandManager instance];
    }
    return _commandM;
}
- (LCCountdownView *)countdownView
{
    if(!_countdownView)
    {
        CGRect rect=[self.containerView convertRect:self.containerView.bounds toView:KeyWindow];
        _countdownView = [[LCCountdownView alloc] initWithFrame:rect];
        
        _countdownView.delegate = self;
    }
    return _countdownView;
}
- (UIButton *)songBtn{
    
    if(!_songBtn){
        _songBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_songBtn setBackgroundImage:[UIImage imageNamed:@"song_nor"] forState:UIControlStateNormal];
        [_songBtn setBackgroundImage:[UIImage imageNamed:@"song_dis"] forState:UIControlStateSelected];
        [_songBtn addTarget:self action:@selector(songBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _songBtn;
}

- (SocketIOTool *)socketTool{
    if(!_socketTool){
        _socketTool = [[SocketIOTool alloc] init];
        _socketTool.url = [QYGKeychain socket_url];
    }
    return _socketTool;
}
- (QYGCurrentRoomView *)currentRoomView{
    if(!_currentRoomView){
        _currentRoomView = [[QYGCurrentRoomView alloc] init];
    }
    return _currentRoomView;
}
- (QYGUserView *)userView{
    if(!_userView){
        _userView = [[QYGUserView alloc] init];
    }
    return _userView;
}

- (UIButton *)changeBtn{
    if(!_changeBtn){
        _changeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_changeBtn setBackgroundImage:[UIImage imageNamed:@"icon_change"] forState:UIControlStateNormal];
        [_changeBtn setBackgroundImage:[UIImage imageNamed:@"icon_change_selected"] forState:UIControlStateHighlighted];
        [_changeBtn addTarget:self action:@selector(changeLiveUrl:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _changeBtn;
}

- (QYGLivePlayManager *)playManager{
    if(!_playManager){
        _playManager = [[QYGLivePlayManager alloc] init];
        _playManager.isTest = [QYGKeychain isDollTest];
        _playManager.delegate = self;
    }
    return _playManager;
}

// 正面视频渲染的view
- (UIView *)f_livePlayerView{
    if(!_f_livePlayerView){
        _f_livePlayerView = [[UIView alloc] init];
    }
    return _f_livePlayerView;
}
// 侧面视频渲染的view
- (UIView *)s_livePlayerView{
    if(!_s_livePlayerView){
        _s_livePlayerView = [[UIView alloc] init];
    }
    return _s_livePlayerView;
}

- (QYGDollBottomView *)dollBottomView{
    if(!_dollBottomView){
        _dollBottomView = [QYGDollBottomView dollBottomView];
        [self.view addSubview:_dollBottomView];
        WS(weakSelf);
        [_dollBottomView setRechargeBtnClickedBlock:^{
            [weakSelf getRechargeList];
        }];
        [_dollBottomView setDetailBtnClickedBlock:^{
            [weakSelf showDetailView];
        }];
        [_dollBottomView setStartBtnClickedBlock:^(CatchStartBtnMode starBtnMode) {
            [weakSelf startButtonClick:starBtnMode];
        }];
        [_dollBottomView setOperationOnClickedBlock:^(NSInteger action) {
            [weakSelf actionButtonOnClicked:action];
        }];
        [_dollBottomView setOperationDownClickedBlock:^(NSInteger action) {
            [weakSelf actionButtonDownClick:action];
        }];
    }
    return _dollBottomView;
}


- (UIView *)containerView{
    if(!_containerView){
        _containerView = [UIView new];
        _containerView.layer.cornerRadius = 4;
        _containerView.layer.masksToBounds = YES;
        [self.view addSubview:_containerView];
    }
    return _containerView;
}

- (QYGDollLoadingView *)loadingView{
    if(!_loadingView){
        _loadingView = [QYGDollLoadingView  dollLoadingView];
    }
    return _loadingView;
}

- (UILabel *)timeLabel{
    if(!_timeLabel)
    {
        _timeLabel =  [UILabel labelWithText:@"" setFont:ScaleBoldFont(30) setTextColor:[UIColor whiteColor] setTextAlignment:NSTextAlignmentRight];
    }
    return _timeLabel;
}
@end

